package com.feiyuan.movie.webmagic.eightens;

import com.feiyuan.common.utils.CommonUtils;
import com.feiyuan.movie.vo.Movie80SJiShuVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 下载80s网站的所有集数
 */
public class Download80SAllMovieProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    private String baseUrl;

    public Download80SAllMovieProcessor(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public Download80SAllMovieProcessor() {}

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }
    public String getBaseUrl() {
        return baseUrl;
    }

    @Override
    public void process(Page page) {
        List<String> allList = page.getHtml().xpath("//ul[@class='dllist1']//li//input/@value").all().stream().filter(item -> {
            if (StringUtils.isNotEmpty(item)) {
                return true;
            }
            return false;
        }).toList();
        String movieType = CommonUtils.getMovieType(baseUrl);
        List<String> jiNames = new ArrayList<>();
        if (movieType.equals("movie")) {
            jiNames = page.getHtml().xpath("//ul[@class='dllist1']//li//span[@class='dlname nm']//a/text()").all();
        }
        List<Movie80SJiShuVO> movie80SJiShuVOS = new ArrayList<>();
        int totalNum = allList.size();
        for (int i=0;i<allList.size();i++) {
            Movie80SJiShuVO movie80SJiShuVO = new Movie80SJiShuVO();
            movie80SJiShuVO.setIndex(i);
            if (!CollectionUtils.isEmpty(jiNames)) {
                movie80SJiShuVO.setPlayName(jiNames.get(i));
            } else {
                movie80SJiShuVO.setPlayName("第" + totalNum + "集");
            }
            movie80SJiShuVO.setPlayUrl(allList.get(i));
            if (StringUtils.isNotEmpty(allList.get(i))) {
                movie80SJiShuVOS.add(movie80SJiShuVO);
            }
            totalNum --;
        }
        page.putField("allJiList", movie80SJiShuVOS);
//        String isEndStr = page.getHtml().xpath("//div[@id='minfo']//div[@class='info']//span[@class='tip']/span/text()").toString();
//        page.putField("isEndStr", isEndStr.replaceAll(" ", ""));
    }

    @Override
    public Site getSite() {
        return site;
    }
}
